package com.jeesuite.monitor.component.jdbc;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jeesuite.monitor.analyser.CommonAnalyser;
import com.jeesuite.monitor.analyser.SessionFilterAnalyser;
import com.jeesuite.monitor.common.asm.ClassEnhancer;
import com.jeesuite.monitor.component.AbstractComponent;
import com.jeesuite.monitor.constant.MonitorContants;
import com.jeesuite.monitor.core.ComponentContext;
import com.jeesuite.monitor.core.TraceManager;
import com.jeesuite.monitor.model.metaobject.Trace.TraceType;

/**
 * Jdbc监控组件
 * @description <br>
 * @author <a href="mailto:vakinge@gmail.com">vakin</a>
 * @date 2016年6月15日
 */
public class JdbcComponent extends AbstractComponent {
	private static final Logger log = LoggerFactory.getLogger(JdbcComponent.class);

	private ComponentContext componentContext = null;

	public void startup(ComponentContext context) {
		componentContext = context;
		
		TraceManager container = componentContext.getContainer();
		container.registerAnalyser(TraceType.JDBC.name(), new CommonAnalyser(TraceType.JDBC.name()));
		container.registerAnalyser(TraceType.JDBC.name(), new SessionFilterAnalyser(TraceType.JDBC.name()));

		String clazzs = context.getProperty(MonitorContants.CONF_DRIVER_CLASS);
		String[] drivers = getDriverClassNames(clazzs);
		// inject trace
		injectJdbcDriver(drivers);
		
		log.info("jdbccomponent startup.");
	}

	private String[] getDriverClassNames(String clazzs) {
		if (clazzs == null || "".equals(clazzs)) {
			return new String[0];
		}
		clazzs = clazzs.replaceAll("\n\r\t\\s+", "");
		try {
			return clazzs.split(";");
		} catch (Exception e) {
			return new String[0];
		}
	}

	private void injectJdbcDriver(String[] drivers) {
		ClassEnhancer enhancer = new ClassEnhancer();
		for (int i = 0; i < drivers.length; i++) {

			String className = drivers[i];
			try {
				TraceManager container = componentContext.getContainer();

				// inject jdbcdriver to delegate connection from local pool or
				// remote pool.
				enhancer.createClass(className, new JdbcDriverInjectHandle(container), true);

			} catch (Exception e) {
				log.warn("对数据库驱动：" + className + "的监听部署失败，不过这并不影响系统的运行。错误原因：\n["
						+ e.getClass().getName() + "-->"+ e.getMessage() + "]");

			}

		}
	}
	

	public void destory() {
	}

	public void clear() {
	}


	public ComponentContext getComponentContext() {
		return componentContext;
	}
}
